
/*
 * This file show how to create a global view independent activity,
 * need to add below permissiom in manifest:
 * <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
 */
import android.app.Service;  
import android.content.BroadcastReceiver;  
import android.content.Context;  
import android.content.Intent;  
import android.graphics.PixelFormat;  
import android.graphics.Rect;  
import android.os.IBinder;  
import android.view.Gravity;  
import android.view.LayoutInflater;  
import android.view.MotionEvent;  
import android.view.View;  
import android.view.WindowManager;  
import android.view.View.OnTouchListener;  
import android.view.WindowManager.LayoutParams;  
import android.widget.ImageView;

public class ViewWithoutActivity extends Service{

	private int statusBarHeight = 0;
	private WindowManager wm;
	private LayoutParams layoutParams;
	private ImageView v;

	@Override
	public IBinder onBind(Intent intent){
		return null;
	}

	@Override
	public void onDestroy(){
		super.onDestroy();
		wm.removeView(v);
	}

	@Override
	public void onCreate(){
		super.onCreate();

		wm = (WindowManager)getSystemService("window");

		layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,
				LayoutParams.TYPE_SYSTEM_ERROR,LayoutParams.FLAG_NOT_FOCUSABLE,
				PixelFormat.TRANSPARENT);
		layoutParams.gravity = Gravity.LEFT | Gravity.TOP;


		v = new ImageView(this);
		v.setImageResource(R.drawable.image);
		v.setOnTouchListener(new OnTouchListener(){

			float[] tmp = new float[]{0f,0f};
			public boolean onTouch(View v,MotionEvent event){

				switch(event.getAction()){
					case MotionEvent.ACTION_DOWN:
						tmp[0] = event.getX();
						tmp[1] = event.getY();
						break;
					case MotionEvent.ACTION_MOVE:
						refreshView((int) (event.getRawX() - tmp[0]), (int)(event.getRawY() - tmp[1]));
						break;
					default:
						break;
				}
				return true;
			}
		});

		wm.addView(v,layoutParams);
	}

	public void refreshView(int x, int y) {  
		if(statusBarHeight == 0){  
			View rootView  = v.getRootView();  
			Rect r = new Rect();  
			rootView.getWindowVisibleDisplayFrame(r);  
			statusBarHeight = r.top;  
		}  

		layoutParams.x = x;  
		layoutParams.y = y - statusBarHeight;
		wm.updateViewLayout(v, layoutParams);  
	} 
}
